//
//  ChooseCarVC.m
//  saler-ios
//
//  Created by 王亚陆 on 17/6/5.
//  Copyright © 2017年 sayimba. All rights reserved.
//

#import "ChooseCarVC.h"

@interface ChooseCarVC ()
<UITableViewDelegate,
UITableViewDataSource,
UITextFieldDelegate
>
{
    UIImageView * nav;
    UITableView * Table;
    RootViewController * TabBar;
    NSMutableDictionary * callBackDic;

    NSMutableArray * ArrData;
    
}
@property (nonatomic,strong) UIView * backview;
@property (nonatomic,strong) UITextField * CarField;
@property (nonatomic,strong) WKProgressHUD *hud;



@end

@implementation ChooseCarVC


- (instancetype)init
{
    self = [super init];
    if (self) {
        self.CarArr = [[NSMutableArray alloc]init];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    nav = [self createNav:@"选择商品车"];
    [self.view addSubview:nav];
    self.view.backgroundColor = UIviewBackColor;
//    ArrData = [NSMutableArray arrayWithObjects:@"西安",@"广州",@"川渝起运",@"武汉", nil];
    
    _backview = [[UIView alloc]init];
    _backview.backgroundColor = WhiteColor;
    [self.view addSubview:_backview];
    [_backview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.view.mas_left).with.offset(10*kWidth);
        make.top.mas_equalTo(nav.mas_bottom).with.offset(10*kHeight);
        make.size.mas_equalTo(CGSizeMake(Main_Width-20*kWidth, Main_height-64-10-10));
    }];
    
    
    callBackDic = [[NSMutableDictionary alloc]init];
    
    
    _CarField = [self createField:@"按照车型名称/首字母/全拼音搜索" andFont:FontOfSize14];
    [_backview addSubview:_CarField];
    [_CarField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_backview.mas_left).with.offset(10*kWidth);
        make.top.mas_equalTo(_backview.mas_top).with.offset(10*kHeight);
        make.size.mas_equalTo(CGSizeMake(Main_Width-36*kWidth, 30*kHeight));
    }];

    UIImageView * image = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"search"]];
    [_backview addSubview:image];
    [image mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(_CarField.mas_left).with.offset(10*kWidth);
        make.centerY.mas_equalTo(_CarField.mas_centerY);
        make.size.mas_equalTo(CGSizeMake(15*kWidth, 15*kHeight));
    }];

    UIView * line = [[UIView alloc]init];
    line.backgroundColor = UIviewBackColor;
    [_backview addSubview:line];
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(_backview.mas_left);
        make.top.mas_equalTo(_CarField.mas_bottom);
        make.size.mas_equalTo(CGSizeMake(Main_Width-20*kWidth, 5*kHeight));
    }];

    
    
    
    Table = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, Main_Width, 86*kHeight) style:UITableViewStylePlain];
    [Table setTableFooterView:[UIView new]];
    
    
    Table.delegate = self;
    Table.dataSource = self;
    Table.sectionIndexBackgroundColor= GrayColor;
    [_backview addSubview:Table];
    [Table mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(_backview.mas_left);
        make.top.mas_equalTo(_CarField.mas_bottom).with.offset(5*kHeight);
        make.size.mas_equalTo(CGSizeMake(Main_Width-20*kWidth, Main_height-64-10-57));
    }];

    

}



-(void)textFieldWithText:(UITextField*)field{
    
    
    NSString * name1 = field.text;
    
    NSString *strUrl = [name1 stringByReplacingOccurrencesOfString:@" " withString:@""];
    
    if (field.text.length>0) {
        
        NSString * url = [NSString stringWithFormat:@"%@/%@",Order_brand,strUrl];
        
        //url汉字转码
        NSString *str1 = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
        
        self.hud  = [WKProgressHUD showInView:self.view withText:@"" animated:YES];


        [Common requestWithUrlString:str1 contentType:application_json finished:^(id responseObj) {
            
            
            NSArray * arr = responseObj[@"data"];
            if (arr.count>0) {
                ArrData = [NSMutableArray arrayWithArray:responseObj[@"data"]];
            }else{
                [ArrData removeAllObjects];
            }
            
            [WKProgressHUD dismissAll:YES];

            [Table reloadData];

            
        } failed:^(NSString *errorMsg) {
            NSLog(@"%@",errorMsg);
            [WKProgressHUD dismissAll:YES];

        }];
    }
    
    else{

        [_CarField resignFirstResponder];
        [ArrData removeAllObjects];
        [Table reloadData];
    }
    
    
}


#pragma mark - 表单协议

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView
 numberOfRowsInSection:(NSInteger)section{
    
    return ArrData.count;
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView
         cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString  *CellIdentifier = @"CellIdentifier";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    if (cell == nil) {
        
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        
    }
    
//    [Table selectRowAtIndexPath:[NSIndexPath indexPathForItem:0 inSection:0] animated:YES scrollPosition:UITableViewScrollPositionNone];
    
//    {
//        brandCode = 10;
//        brandId = 1;
//        brandLogoUrl = "";
//        brandName = "\U5965\U8fea"; 品牌
//        modelCode = 100000;
//        modelId = 1;
//        modelName = "\U54c8\U5f17H6"; 车型
//        seriesCode = 10;
//        seriesId = 1;
//        seriesName = "\U5965\U8feaa1";（车系）
    
//    }

    NSString * carStr = [NSString stringWithFormat:@"%@-%@",ArrData[indexPath.row][@"brandName"],ArrData[indexPath.row][@"seriesName"]];
    cell.textLabel.text = carStr;
    cell.textLabel.textAlignment = NSTextAlignmentCenter;
    cell.textLabel.font = Font(FontOfSize14);
//    cell.selectionStyle = UITableViewCellSelectionStyleNone;

    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView
heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    return  CellHeight;
    
}

- (void)tableView:(UITableView *)tableView
didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    
    BOOL isCar = YES;
    NSString * didCarId = [NSString stringWithFormat:@"%@",ArrData[indexPath.row][@"seriesId"]];
    for (int i= 0; i<self.CarArr.count; i++) {
        
        NSString * carid = [NSString stringWithFormat:@"%@",self.CarArr[i][@"seriesId"]];
        if ([carid isEqualToString:didCarId]) {
            isCar = NO;
        }
    }
    
    if (!isCar) {
        [self  createUIAlertController:@"本车型已选择"];
    }else{
        NSMutableDictionary * dic = [[NSMutableDictionary alloc]init];
        NSMutableDictionary * dic1 = ArrData[indexPath.row];
        dic = dic1.mutableCopy;
        [dic setObject:@"1" forKey:@"amt"];
        if (self.callAddCar) {
            
            self.callAddCar(dic);
        }
        [self.navigationController popViewControllerAnimated:YES];
    }
    
    
    if (self.CarArr.count == 0) {
        
        NSMutableDictionary * dic = [[NSMutableDictionary alloc]init];
        NSMutableDictionary * dic1 = ArrData[indexPath.row];
        dic = dic1.mutableCopy;
        [dic setObject:@"1" forKey:@"amt"];
        if (self.callAddCar) {
            
            self.callAddCar(dic);
        }
        [self.navigationController popViewControllerAnimated:YES];

    }
    

}



-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    
    
    [_CarField resignFirstResponder];
    
    
    
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(UITextField*)createField:(NSString*)placeholder andFont:(double)font{
    
    UITextField * field =[[UITextField alloc]init];
    field.frame = CGRectMake(0, 0, Main_Width-91, 50);
    field.delegate = self;
    field.userInteractionEnabled = YES;
    field.textAlignment = NSTextAlignmentLeft;
    field.keyboardType = UIKeyboardTypeDefault;
    field.backgroundColor = WhiteColor;
    field.layer.cornerRadius = 5;
    field.layer.borderWidth = 0.5;
    field.layer.borderColor = WhiteColor.CGColor;
    
    // 为了给textField添加一个图片，创建一个imageView
    UIImageView *accLeftView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"icon_search"]];
    accLeftView.frame = CGRectMake(20, 5, 24, 13);
    //    accLeftView.contentMode = UIViewContentModeLeft;
    // 添加到左侧视图中
    field.leftView = accLeftView;
    field.leftViewMode = UITextFieldViewModeAlways; // 这句一定要加，否则不显示
    
    field.placeholder =placeholder;
    [field setFont:[UIFont fontWithName:@"STHeitiSC" size:font]];
    [field addTarget:self action:@selector(textFieldWithText:) forControlEvents:UIControlEventEditingChanged];
//    [field addTarget:self action:@selector(textFieldWithText1:) forControlEvents:UIControlEventEditingDidBegin];
    [field placeholderRectForBounds:CGRectMake(100.0, 100.0, 100, 100)];
    
    
    return field;
}
-(void)createUIAlertController:(NSString*)title
{
    UIAlertController * alert =[UIAlertController alertControllerWithTitle:@"提示" message:title preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction * action =[UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        
        
    }];
    UIAlertAction * action1 =[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    }];
    [alert addAction:action1];
    [alert addAction:action];
    [self presentViewController:alert animated:YES completion:nil];
}

@end
